<template>
  <div>
    <van-nav-bar title="账号登录" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        placeholder="请输入账号"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <router-link to="/register">还没有账号？去注册~~</router-link>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { setToken, getToken } from '@/utils/storage'
export default {
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async onSubmit (values) {
      const res = await login(values)
      setToken(res.body.token)
      if (res.status === 200) this.$router.push('/')
    },
    onClickLeft () {
      if (!getToken()) {
        this.$toast.fail('请先登录')
      } else {
        this.$router.push('/user')
      }
    }
  }
}
</script>

<style scoped>
a {
  display: block;
  margin: 0 auto;
  text-align: center;
  text-decoration: none;
  font-size: 0.175rem;
  color: #666;
}
</style>
